package com.duoec.magichour.core.utils;

import com.duoec.magichour.core.CommonConst;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by ycoe on 17/3/10.
 */
public class FileCacheUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileCacheUtils.class);

    /**
     * 文件内容MAP：filePath => fileContent
     */
    private static final Map<String, String> FILE_CONTENT_MAP = Maps.newConcurrentMap();

    /**
     * 文件key map: md5(filePath) => lastModified
     */
    private static final Map<String, Long> FILE_KEY_MODIFY_MAP = Maps.newConcurrentMap();

    private FileCacheUtils() {
        //Do Nothing
    }

    public static void set(String key, File file) {
        Long modify = FILE_KEY_MODIFY_MAP.get(key);
        String filePath = file.getAbsolutePath();
        long lastModified = file.lastModified();
        if (modify != null) {
            //已经存在，尝试检查是否过期
            if (!modify.equals(lastModified)) {
                //有更新！删除缓存！
                FILE_CONTENT_MAP.remove(filePath);
                FILE_KEY_MODIFY_MAP.put(key, lastModified);
            }
        } else {
            FILE_KEY_MODIFY_MAP.put(key, lastModified);
        }
    }

    public static String readFileToString(File file) {
        String filePath = file.getAbsolutePath();
        if (FILE_CONTENT_MAP.containsKey(filePath)) {
            return FILE_CONTENT_MAP.get(filePath);
        }

        StringBuilder content = new StringBuilder();
        try {
            Files.readLines(file, Charset.forName(CommonConst.ENCODE)).forEach((str) -> {
                content.append(str);
                content.append("\n");
            });
        } catch (IOException e) {
            logger.error("读取文件[{}]失败", filePath, e);
        }
        FILE_CONTENT_MAP.put(filePath, content.toString());

        return content.toString();
    }
}
